package com.bdqn.mongodb2.controller;

import com.bdqn.mongodb2.entity.Book;
import com.bdqn.mongodb2.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    //基础查询（CRUD）
    @GetMapping("/books")
    public ModelAndView books(){
        List<Book> books=bookService.findAllBooks();
        ModelAndView mv=new ModelAndView();
        mv.addObject("books",books);
        mv.setViewName("books");
        return mv;
    }

    @GetMapping("/book/{id}")
    public ModelAndView findStudentById(@PathVariable("id") int id){
        Book book= (Book) bookService.findBookById(id);
        ModelAndView mv=new ModelAndView();
        mv.addObject("book",book);
        mv.setViewName("book");
        return mv;

    }

    @GetMapping("/addBook")
    public String addStudent(){
        return "addBook";
    }

    @PostMapping("/addBook")
    public ModelAndView addStudent(Book book){
        bookService.addBook(book);
        ModelAndView mv=new ModelAndView();
        mv.setViewName("redirect:/books");//添加成功后，跳转到查找所有学生的控制器
        return mv;
    }



    @GetMapping("/deleteBook/{id}")
    public ModelAndView deleteStudent(@PathVariable("id") int id){
        bookService.deleteBook(id);
        ModelAndView mv=new ModelAndView();
        mv.setViewName("redirect:/books");//删除成功后，跳转到查找所有学生的控制器
        return mv;
    }

    @GetMapping("/updateBook/{id}")
    public ModelAndView toUpdateStudent(@PathVariable("id") int id){
        Book book= (Book) bookService.findBookById(id);
        ModelAndView mv=new ModelAndView();
        mv.addObject("book",book);
        mv.setViewName("updateBook");
        return mv;
    }

    @PostMapping("/updateBook")
    public ModelAndView UpdateStudent(Book book){
        bookService.updateBook(book);
        ModelAndView mv=new ModelAndView();
        mv.setViewName("redirect:/books");//修改成功后，跳转到查找所有学生的控制器
        return mv;
    }



    //模糊查询
    @GetMapping("/searchBook")
    public ModelAndView searchBook(String name){
        List<Book> books=bookService.findLike(name);
        ModelAndView mv=new ModelAndView();
        mv.addObject("books",books);
        mv.setViewName("books");
        return mv;
    }



}
